package com.example.zbh.dsliao.ui.activty;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.zbh.dsliao.MusicIdle;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.constant.Constant;
import com.example.zbh.dsliao.model.entity.NetSongList;
import com.example.zbh.dsliao.presenter.HotSongMenuPresenter;
import com.example.zbh.dsliao.ui.adapter.HotMenuSongListAdapter;
import com.example.zbh.dsliao.ui.viewinterface.ShowDownLoaderResultListener;
import com.example.zbh.dsliao.utils.FormatTime;
import com.example.zbh.dsliao.utils.FullyGridLayoutManager;
import com.example.zbh.dsliao.utils.MyEventBus;
import com.example.zbh.dsliao.utils.net.VolleySingleton;
import com.example.zbh.dsliao.view.CustomDialog;
import com.example.zbh.dsliao.view.PowerImageView;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by yaolin on 15/11/26.
 */
public class HotSongMenuActivity extends MVPBaseActivity<ShowDownLoaderResultListener, HotSongMenuPresenter> implements HotMenuSongListAdapter.setOnClickListener, View.OnClickListener, SeekBar.OnSeekBarChangeListener, ShowDownLoaderResultListener {
    private TextView song, titleTv, maxTv, progressTv;
    private ImageView img_play, img_previous, img_next, img_order, img_radom, img_single, img_back;
    private SeekBar progress;


    //获得值
    private long id;
    private String title;

    //列表
    private RecyclerView hotList;
    //适配器
    private HotMenuSongListAdapter adapter;

    //自定义dialog
    private CustomDialog customDialog;


    private final static String mode_random = "RADOM_MODE"; //随机播放
    private final static String mode_order = "ORDER_MODE"; //循环播放
    private final static String mode_single = "SINGLE_MODE"; //单曲循环
    private int random;         //随机数
    private int currentIndex;    //当前播放位置

    //广播
    private BroadcastReceiver HotSongMenuBroadCast;
    //集合
    private List<NetSongList> list;

    //网络请求
    VolleySingleton volleySingleton = VolleySingleton.getInstance();

    //接口操作对象
    private MusicIdle musicIdle;
    //远程服务
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //初始化操作对象
            musicIdle = MusicIdle.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };


    @Override
    protected int getLayOut() {
        return R.layout.activity_song_list;
    }

    @Override
    protected void initView() {
        titleTv = (TextView) findViewById(R.id.titleTv);

        img_back = findeView(R.id.img_back);
        img_back.setOnClickListener(this);

        img_play = findeView(R.id.img_play);                    //播放按钮
        img_play.setOnClickListener(this);

        img_previous = findeView(R.id.img_previous);            //上一首
        img_previous.setOnClickListener(this);

        img_next = findeView(R.id.img_next);                    //下一首
        img_next.setOnClickListener(this);

        song = findeView(R.id.song);                           //歌名 + 歌手
        maxTv = findeView(R.id.tv_time_max);                    //歌曲时长
        progressTv = findeView(R.id.tv_time_progress);         //当前时长

        progress = findeView(R.id.progress);                   //拖动条
        progress.setOnSeekBarChangeListener(this);


        img_order = (ImageView) findViewById(R.id.img_order);   //循环播放
        img_order.setOnClickListener(this);

        img_radom = (ImageView) findViewById(R.id.img_radom);   //随机播放
        img_radom.setOnClickListener(this);

        img_single = (ImageView) findViewById(R.id.img_single); //单曲播放
        img_single.setOnClickListener(this);

        progress = (SeekBar) findViewById(R.id.progress);
        progress.setOnSeekBarChangeListener(this);


        hotList = findeView(R.id.listView);
        FullyGridLayoutManager gm = new FullyGridLayoutManager(this, 1);
        hotList.setLayoutManager(gm);

        adapter = new HotMenuSongListAdapter(this);
        hotList.setAdapter(adapter);
        adapter.setListener(this);

    }


    @Override
    protected void initData() {
        //初始化dialog
        customDialog = new CustomDialog(this, "玩命加载中...");
        //注册EventBus
        EventBus.getDefault().register(this);

        //获得值
        getData();
        //网络请求
        createPresenter().startHotSongMenuConnection(getUrl());

        //绑定服务
        Intent it = new Intent("com.lanou.service.player");
        bindService(it, conn, BIND_AUTO_CREATE);

        //注册广播
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.lanou.player.next");
        filter.addAction("com.lanou.player.previous");
        filter.addAction("com.lanou.player.radomPlay");
        filter.addAction("com.lanou.player.singlelay");
        HotSongMenuBroadCast = new HotSongMenuBroadCast();
        registerReceiver(HotSongMenuBroadCast, filter);

    }


    //当前进度
    public void onEvent(MyEventBus.CurrentIndex currentIndex) {
        progressTv.setText(FormatTime.formatTime((long) currentIndex.getCurrentIndex()));
        progress.setProgress(currentIndex.getCurrentIndex());
    }


    //最大进度
    public void onEvent(MyEventBus.MaxProgress maxProgress) {
        maxTv.setText(FormatTime.formatTime((long) maxProgress.getMaxProgress()));
        progress.setMax(maxProgress.getMaxProgress());
    }


    //随机数
    public void onEvent(MyEventBus.RandomMode randomMode) {
        this.random = randomMode.getPlayerRandom();
        Log.i("lanou3g", "随机播放模式的随机数:" + this.random);
    }

    @Override
    public void showResult(List list) {
        this.list = list;
        adapter.addData(list);
    }

    @Override
    public void showOtherResult(List list) {

    }


    //广播
    public class HotSongMenuBroadCast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("com.lanou.player.next")) {
                if (musicIdle != null) {
                    currentIndex++;
                    Log.i("lanou3g", "循环模式:" + currentIndex);
                }
            } else if (intent.getAction().equals("com.lanou.player.previous")) {
                if (musicIdle != null) {
                    currentIndex--;
                    Log.i("lanou3g", "上一首:" + currentIndex);
                }
            } else if (intent.getAction().equals("com.lanou.player.radomPlay")) {
                if (musicIdle != null) {
                    currentIndex = random;
                    Log.i("lanou3g", "随机模式:" + currentIndex);
                }
            } else if (intent.getAction().equals("com.lanou.player.singlelay")) {
                if (musicIdle != null) {
                    currentIndex = currentIndex;
                    Log.i("lanou3g", "单曲循环:" + currentIndex);
                }
            }
            song.setText(list.get(currentIndex % list.size()).getName() + "          "
                    + list.get(currentIndex % list.size()).getSingerName());

            String url = list.get(currentIndex % list.size()).getAuditionList().get(0).getUrl();

            try {
                if (musicIdle != null) {
                    musicIdle.setUrl(url);
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }


    //获得值
    private void getData() {
        Intent intent = getIntent();
        id = intent.getLongExtra("id", -1);
        title = intent.getStringExtra("title");
        titleTv.setText(title);
        titleTv.setTextSize(15);
    }


    @Override
    protected HotSongMenuPresenter createPresenter() {
        return new HotSongMenuPresenter(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册
        EventBus.getDefault().unregister(this);
        //解绑服务
        unbindService(conn);
    }

    public String getUrl() {
        return Constant.HOTSONGMENUFRONTURL + id + Constant.HOTSONGMENULATERURL;
    }

    //列表行点击事件 @Override
    public void onItemClick(NetSongList list, int position) {
        try {
            if (musicIdle != null && list != null && list.getAuditionList() != null
                    && list.getAuditionList().size() > 0) {
                musicIdle.setUrl(list.getAuditionList().get(0).getUrl());
                song.setText(list.getName() + "      " + list.getSingerName());
                img_play.setImageResource(R.mipmap.deep_pause_btn);
                currentIndex = position;

            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.img_play:  //暂停
                pause();
                break;
            case R.id.img_previous:  //上一首
                previous();
                break;

            case R.id.img_next:      //下一首
                next();
                break;
            case R.id.img_order:  //随机播放
                radom();
                break;

            case R.id.img_radom:  //单曲播放
                single();
                break;

            case R.id.img_single:   //循环播放
                order();
                break;
        }
    }

    /**循环播放**/
    private void order() {
        img_order.setVisibility(View.VISIBLE);
        img_radom.setVisibility(View.GONE);
        img_single.setVisibility(View.GONE);
        Toast.makeText(this, "循环播放", Toast.LENGTH_SHORT).show();
        EventBus.getDefault().post(new MyEventBus.PlayerMode(mode_order));
    }

    /**单曲播放**/
    private void single() {
        img_order.setVisibility(View.GONE);
        img_radom.setVisibility(View.GONE);
        img_single.setVisibility(View.VISIBLE);
        Toast.makeText(this, "单曲播放", Toast.LENGTH_SHORT).show();
        EventBus.getDefault().post(new MyEventBus.PlayerMode(mode_single));
    }

    /**随机播放**/
    private void radom() {
        img_order.setVisibility(View.GONE);
        img_radom.setVisibility(View.VISIBLE);
        img_single.setVisibility(View.GONE);

        EventBus.getDefault().post(new MyEventBus.PlayerMode(mode_random));
        Toast.makeText(this, "随机播放", Toast.LENGTH_SHORT).show();
    }

    /**下一首**/
    private void next() {
        try {
            if (musicIdle != null) {
                musicIdle.next();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**上一首**/
    private void previous() {
        try {
            if (musicIdle != null) {
                musicIdle.previous();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**暂停**/
    private void pause() {
        if (musicIdle != null) {
            try {
                musicIdle.pause();
                img_play.setImageResource(R.mipmap.deep_play_btn);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (musicIdle != null) {
            try {
                musicIdle.setProgress(seekBar.getProgress());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }





    }
}
